<?php
function getShowList () {
	global $db;
	$ret = array();
	if($res = $db->query("select ID, NAME from SHOWS order by DATE_CREATED desc")) {
		while($row = $res->fetch_assoc()){
			$ret[] = $row;
		}
	} 
	return $ret;
}

function savePlaylist($data){
	global $db;
	$song_id = 0;
	$key = 0;
	
	$stmt = $db->prepare("update SONGS set SEQ_NO = ? where ID = ?");
	$stmt->bind_param("ii", $key, $song_id);
	
	foreach($data["playlist"] as $key => $song_id){
		$stmt->execute();
	}
	$stmt->close();
}

function deleteSong($d){
	global $db;
	
	$id = $d["id"];
	
	if ($id > 0){	
		$stmt = $db->prepare("delete from SONGS where ID = ?");
		$stmt->bind_param("i", $id);
		$stmt->execute();
		$stmt->close();
	};
}
	


function saveSong($d){
	global $db;
	
	$id = $d["id"];
	
	if ($id > 0){	
		$stmt = $db->prepare("update SONGS set 
			ARTIST = ?,
			TITLE = ?,	
			YEAR = ?,
			DESCRIPTION = ?
			where ID = ?
		");
		$stmt->bind_param("ssssi", $d["artist"], $d["title"], $d["year"], $d["description"], $id);
		$stmt->execute();
	} else {
		$stmt = $db->prepare("insert into SONGS set 
			ARTIST = ?,
			TITLE = ?,
			SEQ_NO = ?,	
			YEAR = ?,
			DESCRIPTION = ?,
			SHOW_ID = ? 
		");
		$stmt->bind_param("ssissi", $d["artist"], $d["title"], time(), $d["year"], $d["description"], $d["show_id"]);
		$stmt->execute();
		$id = $stmt->insert_id;
	}
	
	$stmt->close();
	
	return $id;
}

function getSongs ($showId) {
	global $db;
	$showId = $showId + 0;
	if ($showId > 0) {
		$ret = array();
		if($res = $db->query("select * from SONGS where SHOW_ID = $showId order by SEQ_NO asc")) {
			while($row = $res->fetch_assoc()){
				$ret[] = $row;
			}
		} 
		return $ret;
	}
	return null;
}

function getSong ($id) {
	global $db;	
	$id = $id + 0;
	if($res = $db->query("select * from SONGS where ID = $id")) {
		if($row = $res->fetch_assoc()){
			return $row;
		}
	} 
	return null;
}


function getShow ($id) {
	global $db;
	$id = $id + 0; // Escape the ID
	if ($id > 0) {
		if($res = $db->query("select * from SHOWS where ID = $id")) {
			if($row = $res->fetch_assoc()){
				return $row;
			}
		} 
	}
	return null;
}

switch($cmd[1]){
	case "getpage": 
		$showlist = getShowList();
		if(count($showlist) > 0) {
			$id = $showlist[0]["ID"];
		}
		return json_encode(
			array(
				"showlist" => $showlist,
				"show" => getShow($id),
				"songs" => getSongs($id)
			)
		);
	case "saveplaylist": 
		savePlaylist($_POST["data"]);
		break;
	case "savesong": 
		$save_id = saveSong($_POST["data"]);
		return json_encode(
			array(
				"songs" => getSongs($_POST["data"]["show_id"]),
				"song" => getSong($save_id)
			)
		);
	case "deletesong": 
		$save_id = deleteSong($_POST["data"]);
		return json_encode(
			array(
				"songs" => getSongs($_POST["data"]["show_id"])
			)
		);
}
return "";
?>